from django.views import View
from product.models import Product
from django.http import JsonResponse
# Create your views here.

class IndexView(View):
    
    # 登录需要写在请求方法执行前

    def get(self, request):
       
        print("进入到get 请求了")
        products = Product.objects.all()
        data_list = []
        for product in products:
            
            data = {
                "name": product.product_name,
                "cover": product.cover.url if product.cover else None,
                "price": product.price,
                "popularity": product.popularity,
                "stock": product.stock,
                "is_active": product.is_active,
            }
            data_list.append(data)
        # 返回json 数据，当前的数据保存在列表中，不是字典，需要使用safe=True, 非字典数据，也能返回
        return JsonResponse(data=data_list, safe=False)
    

    def post(self, request):
        print("进入到post 请求了")
        # 响应返回之前
        return JsonResponse(data={"message": "post 请求成功"}, safe=False)
        
